<?php

namespace App\Http\Controllers;

use App\Http\Requests\IndexDicdataRequest;
use App\Http\Requests\StoreDicdataRequest;
use App\Http\Requests\UpdateDicdataRequest;
use App\Http\Resources\DicdataResource;
use App\Models\Dicdata;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Validator;

class DicdataController extends Controller
{
    public function __construct()
    {
        $this->middleware('auth:sanctum');
    }
    /**
     * Display a listing of the resource.
     */
    public function index(IndexDicdataRequest $request, Dicdata $dicdata)
    {
        $this->authorize('viewAny', $dicdata);
        $typeCode = $request->query('typeCode');
        $query = $dicdata->where('typeCode', $typeCode);

        // 根据 $keywords 和 $status 添加动态查询条件
        if ($request->filled('name')) {
            $name = $request->query('name');
            $query->where('name', 'like', "%$name%");
        }

        $data = $query->orderBy('order')
            ->paginate($request->query('pageSize'), ['*'], 'page', $request->query('pageNum'));

        $response = DicdataResource::collection($data);
        $total = $data->total(); // 获取分页信息中的总数
        return $this->success('查询成功', $response, $total);
    }

    public function options(Request $request, Dicdata $dicdata)
    {
        Validator::make($request->input(), [
            'option' => ['required', 'array']
        ])->validate();
        $option = $request->input('option');
        $data = $dicdata->orderBy('order', 'ASC')->where('status', 1)->whereIn('typeCode', $option)
            ->select('name as label', 'value as value', 'typeCode')->get();
        $formattedData = [];
        foreach ($data as $item) {
            $formattedData[$item->typeCode][] = [
                'label' => $item->label,
                'value' => $item->value,
            ];
        };

        return $this->success('查询成功', $formattedData);
    }

    /**
     * 获取非字典比如分类下拉框数据
     */
    public function selectoption(Request $request, $type)
    {
        $model = modelClass($type);
        $data = $model::select('name as label', 'id as value')->get();
        return $this->success('查询成功', $data);
    }

    /**
     * Show the form for creating a new resource.
     */
    public function create()
    {
        //
    }

    /**
     * Store a newly created resource in storage.
     */
    public function store(StoreDicdataRequest $request, Dicdata $dicdata)
    {
        $this->authorize('create', $dicdata);
        // 检查是否已存在相同的code
        $exists = Dicdata::where('typeCode', $request->input('typeCode'))
            ->where('value', $request->input('value'))->exists();
        if ($exists) {
            return $this->error('value 已经存在，无法新增重复的 value');
        }

        $dicdata->fill($request->input());
        $dicdata->save();
        return $this->success('新增成功', $dicdata);
    }

    /**
     * Display the specified resource.
     */
    public function show(Dicdata $dicdata, $id)
    {
        $dicdata = $dicdata->findOrFail($id);
        $this->authorize('viewAny', $dicdata);
        return $this->success('查询成功', new DicdataResource($dicdata));
    }

    /**
     * Show the form for editing the specified resource.
     */
    public function edit(Dicdata $dicdata)
    {
        //
    }

    /**
     * Update the specified resource in storage.
     */
    public function update(UpdateDicdataRequest $request, Dicdata $dicdata, $id)
    {
        $this->authorize('update', $dicdata);
        // 检查是否已存在相同的code
        $exists = Dicdata::where('typeCode', $request->input('typeCode'))
            ->where('value', $request->input('value'))
            ->where('id', '!=', $id) // 排除当前记录
            ->exists();
        if ($exists) {
            return $this->error('value 已经存在，无法新增重复的 value');
        }
        $dicdata = $dicdata->findOrFail($id);
        $dicdata->fill($request->input());
        $dicdata->save();
        return $this->success('编辑成功', new DicDataResource($dicdata));
    }

    /**
     * Remove the specified resource from storage.
     */
    public function destroy(Dicdata $dicdata, $id)
    {
        $dicdata = $dicdata->findOrFail($id);
        $this->authorize('delete', $dicdata);
        $dicdata->delete();
        return $this->success('删除成功', $dicdata);
    }
}
